//本地存储 localstore 名称
const storeName = "shopStore";
//无任何勾选时的默认访问地址
const defSite = "https://s.taobao.com/search?q={s}";
//本地存储 内容
const siteStore = window.localStorage.getItem(storeName);
//layui form对象
const form = layui.form;

$(function () {
    /** 回显复选框 */
    if (siteStore && siteStore.length > 0) {
        siteStore.split(",").forEach(t => $(":checkbox[name='site'][value='" + t + "']").prop("checked", true));
        form.render('checkbox');
    }

    /** 点击搜索引擎时更新存储 */
    form.on('checkbox(mysite)', function (data) {
        const siteArr = $(":checkbox[name='site']:checked");
        let siteStr = "";
        siteArr.each(function (i) {
            if (i !== 0) {
                siteStr += ",";
            }
            siteStr += $(this).val();
        });
        window.localStorage.setItem(storeName, siteStr);
    });

    /** 执行搜索 */
    $(".search").click(search);
    $("#content").keydown(function (e) {
        if (e.key === "Enter") {
            search();
        }
    });
});

/** 搜索业务方法 */
function search() {
    let content = $("#content").val();
    const siteArr = $(":checkbox[name='site']:checked");
    if (!siteArr || siteArr.length === 0) {
        window.location.href = defSite.replace("{s}", content);
    }

    siteArr.each(function (i) {
        if (i < siteArr.length - 1) {
            window.open($(this).val().replace("{s}", content), "_blank");
        } else {
            window.location.href = $(this).val().replace("{s}", content);
        }
    });
}